const Common = require('./constants').default
import { getSecret } from './keystore'
const fs = require('fs')

function removeKeystore(publickey,pwd,callback){
    console.log('removekeystore',publickey,pwd)
    var keystore_path = Common.DEFAULT_KEYSTORE_PATH
    var files = fs.readdirSync(keystore_path).sort()
    if(!publickey||!pwd){
        return callback({code:0,msg:'Expectation publick and pwd'})
    }
    // console.log(keystore_path)
    files.forEach(function(file,index){
        var err_status = false
        try{
            var keystore_json = fs.readFileSync(keystore_path+'/'+file).toString('utf-8')
            // console.log(keystore_json)
            // console.log(typeof keystore_json)
            var keystore_obj = JSON.parse(keystore_json)
            // console.log(keystore_obj.publicKey)
        }catch(err){
            // console.error('removekeystore',err)
            err_status = true
        }
        if(!err_status){
            if (keystore_obj.publicKey == publickey){
                // console.log("12")
                getSecret(keystore_obj,pwd,function(resp_gets){
                    if (resp_gets.code){
                        try{
                            fs.unlinkSync(keystore_path+'/'+file)
                        }catch(err){
                            callback({code:0,msg:err})
                            return false
                        }
                        // console.log("123")
                        callback({code:200,msg:publickey+' removed.'})
                        return false
                    } else {
                        callback(resp_gets)
                        return false
                    }
                })   
            }         
        }
                     
    })
}

export default removeKeystore